package com.rf.richfitwheel.admin.shiro.filter;

import com.rf.richfitwheel.common.utils.JsonUtils;
import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.common.utils.StringUtils;
import net.sf.json.JSONObject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * shiro session失效处理
 * @author hushouquan
 *
 */
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter{
	
//	@Autowired
//	private CommonPropertiesConfig commonPropertiesConfig;
	
	private String feignAccessToken;
	
	/**
	 * 
	 * @param feignAccessToken
	 */
	public CustomFormAuthenticationFilter(String feignAccessToken) {
		this.feignAccessToken=feignAccessToken;
	}

	@Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //Always return true if the request's method is OPTIONS
        if (request instanceof HttpServletRequest) {
            if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
                return true;
            }
        }
        //含有feignAccessToken说明是feign调用，token匹配则直接通过验证
        String accessToken = ((HttpServletRequest) request).getHeader("feignAccessToken");
		if(StringUtils.isBlank(accessToken)){
			accessToken = request.getParameter("feignAccessToken");
		}
        if(feignAccessToken.equals(accessToken)) {
        	return true;
        }
       return super.isAccessAllowed(request, response, mappedValue);
    }
	
	@Override  
    protected boolean onAccessDenied(ServletRequest arg0, ServletResponse arg1) throws Exception {  
		HttpServletRequest request =(HttpServletRequest) arg0;
		HttpServletResponse response =(HttpServletResponse) arg1;
//		String requestURI = getPathWithinApplication(arg0);
//		System.out.print("requestURI"+requestURI);
		
		try {
			JSONObject returnObj = new JSONObject();
			returnObj.optString("httpCode", "SHIRO_EXPIRE");//shiro session 获取
			response.setContentType("application/json; charset=utf-8");
			response.setCharacterEncoding("UTF-8");
			R r = R.error(HttpStatus.UNAUTHORIZED.value(), "由于权限不足请求被拒绝");//没权限直接返回401
			if(request.getRequestURI().contains("wftask/getTaskInfoById")){
				r.put("reLogin", true);
			}
			response.getWriter().write(JsonUtils.mapToJson(r));
			response.getWriter().close();
		} catch (IOException e) {
		   e.printStackTrace();
		}
		return false;
    }
}
